package com.milling.business.service;

import com.milling.common.utils.uuid.UUID;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import java.util.Map;
import java.util.concurrent.*;

@Component
public class SuspendTaskManager {
    private final Map<String, CompletableFuture<Boolean>> taskMap = new ConcurrentHashMap<>();

    // 注册挂起任务
    public String registerTask() {
        String token = UUID.randomUUID().toString();
        taskMap.put(token, new CompletableFuture<>());
        return token;
    }

    // 等待用户响应（阻塞线程）
    public boolean awaitUserDecision(String token, long timeout, TimeUnit unit)
            throws InterruptedException, TimeoutException, ExecutionException {
        return taskMap.get(token).get(timeout, unit);
    }

    // 处理用户响应
    public void resolveTask(String token, boolean userConfirm) {
        if (!taskMap.containsKey(token)) {
            throw new IllegalStateException("无效的任务令牌");
        }
        // ...原有逻辑
        taskMap.get(token).complete(userConfirm);
        taskMap.remove(token);
    }

    @Scheduled(fixedRate = 60_000)
    public void cleanExpiredTokens() {
        taskMap.entrySet().removeIf(entry ->
                entry.getValue().isDone() ||
                        entry.getValue().isCancelled()
        );
    }

}
